﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ZDT.Task.Entity;
using ZDT.Task.Plan;

namespace ZDT.Task.Job
{
    public class TaskItemJob<T, U> : TaskItem
    {
        public TaskItemJob(T setting, U result, ISchedule schedule)
            : base(schedule)
        {
            this.Setting = setting;
            this.Result = result;
        }
        public TaskItemJob(PlanItem<T> planItem, U result)
            : base(planItem.Schedule)
        {
            this.Setting = planItem.Setting;
            this.Result = result;
        }
        public T Setting { get; set; }
        public U Result { get; set; }
        public int ThreadCount { get; set; }

        public virtual void Execute(object param)
        {
            base.Execute(param);
            for (int k = 0; k < ThreadCount; k++)
            {
                var one = GetNextOne(param);
                ThreadPool.QueueUserWorkItem(ExecuteOne, one);
            }
        }
        private LinkedList<WorkItem<T>> workItems = new LinkedList<WorkItem<T>>();
        protected virtual WorkItem<T> GetNextOne(object param)
        {
            var first = workItems.First;
            WorkItem<T> result = null;
            if (first != null)
            {
                result = first.Value;
                workItems.RemoveFirst();
            }
            return result;
        }
        protected virtual void Init()
        {
            base.Init();
        }
        protected virtual void ExecuteOne(object param)
        {

        }
        protected virtual void AddWorkItem(WorkItem<T> workItem)
        {
            workItems.AddLast(workItem);
        }
    }
}
